package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜品 服务层实现类
 * @Description:
 **/
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorMapper flavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;


    /**
     * 添加菜品以及对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional   //事务管理
    public void addDish(DishDTO dishDTO) {
        log.info("菜品服务层实现类");

        Dish dish = new Dish();
        //对象属性拷贝
        BeanUtils.copyProperties(dishDTO, dish);
        //设置创建人id、创建时间，修改人id，修改时间
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        //设置菜品状态，默认停售
        dish.setStatus(StatusConstant.DISABLE);

        log.info("数据添加前的菜品信息为：{}", dish);
        //向菜品表中插入一条数据
        dishMapper.insert(dish);
        log.info("数据添加后的菜品信息为：{}", dish);

        //获取 菜品id
        //TODO 获取新增mysql数据后 回显的的id值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断是否有菜品口味
        if(flavors != null && flavors.size() > 0){
            //向菜品口味表中插入多条数据
            flavors.stream()
                .forEach(flavor -> {
                    //设置菜品id
                    flavor.setDishId(dishId);
                    //插入数据
                    flavorMapper.insert(flavor);
                });
        }


    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult findPageDish(DishPageQueryDTO dishPageQueryDTO) {
        //开始分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //查询菜品信息
        Page<DishVO> page = dishMapper.findPageDish(dishPageQueryDTO);
        log.info("分页查询菜品信息：{}", page);
        return new PageResult(page.getPages(),page.getResult());

    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断菜品是否可以被删除 ---> 状态为起售则不可以删除
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if(dish.getStatus().equals(StatusConstant.ENABLE)){
                throw new RuntimeException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        //判断菜品是否可以被删除 ---> 被套餐关联则不能删除
        for(Long id : ids){
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(id);
            if(setmealIds.size() > 0){
                throw new RuntimeException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
//        /**
//         * 未优化sql 语句
//         */
//        //删除菜品
//        for (Long id : ids){
//            dishMapper.deleteById(id);
//            //删除菜品对应的口味
//            flavorMapper.deleteByDishId(id);
//        }

        /**
         * 优化sql  语句，使用批量删除
         */
        //根据id集合批量删除菜品
        //sql:delete from dish where id in (?,?,?)
        dishMapper.deleteByIds(ids);
        //根据id集合批量删除菜品对应的口味
        //sql:delete from dish_flavor where dish_id in (?,?,?)
        flavorMapper.deleteByDishIds(ids);

    }

    /**
     * 根据id查询菜品和对应的口味
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishVO selectDishAndFlavorById(Long id) {
        //根据id查询菜品信息
        Dish dish = dishMapper.selectById(id);
        //根据id查询菜品对应的口味信息
        List<DishFlavor> flavors = flavorMapper.getByDishId(id);
        //将菜品信息和对应的口味信息集合封装到DishVO中并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        log.info("根据id查询菜品和对应的口味：{}", dishVO);
        return dishVO;
    }

    /**
     * 根据菜品id修改菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateById(DishDTO dishDTO) {
        //修改菜品表数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setUpdateTime(LocalDateTime.now()); //设置修改时间
        dish.setUpdateUser(BaseContext.getCurrentId()); //设置修改人id
        log.info("修改菜品表数据：{}", dish);
        dishMapper.updateById(dish);
        //删除菜品对应的所有口味数据
        flavorMapper.deleteByDishId(dishDTO.getId());
        //添加新的口味数据
        if(dishDTO.getFlavors().size() > 0){
            dishDTO.getFlavors().stream()
                    .forEach(flavor -> {
                        flavor.setDishId(dishDTO.getId());
                        flavorMapper.insert(flavor);
                    });
        }
    }

    /**
     * 根据菜品id修改菜品启售停售状态
     * @param status
     * @param id
     */
    @Override
    public void updateStatusById(Integer status, Long id) {
       dishMapper.updateStatusById(status, id);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
}
